<template>
  <view class="container">
    <uv-navbar 
      class="bold-title" 
      title="检疫管理记录" 
      @leftClick="goBack"
      :safeAreaInsetTop="true"
      :placeholder="true"
      :height="'44px'"
    ></uv-navbar>
    
    <view class="content-area">
      <InfoTitleList :infoTitleList="animalInfoList0"></InfoTitleList>
      
      <view class="form-item">
        <text class="label">检疫单位</text>
        <input v-model="formData.F_Stand" placeholder="雷山县动物卫生监督所" class="input" />
      </view>
      
      <view class="form-item">
        <text class="label">检疫类型</text>
        <input v-model="formData.F_Title" placeholder="请输入检疫类型" class="input" />
      </view>
      
      <view class="form-item">
        <text class="label">检疫人员电话</text>
        <input v-model="formData.F_Phone" placeholder="请输入检疫人员电话" class="input" type="number" />
      </view>
      
      <view class="form-item">
        <text class="label">检疫人员姓名</text>
        <input v-model="formData.F_Personnel" placeholder="请输入检疫人员姓名" class="input" />
      </view>
      
      <view class="form-item">
        <text class="label">检疫地址</text>
        <input v-model="formData.F_Address" placeholder="请输入检疫地址" class="input" />
      </view>
      
      <view class="form-item">
        <text class="label">检疫结果</text>
        <picker 
          :value="formData.F_Level" 
          :range="resultOptions" 
          range-key="id" 
          @change="onResultChange"
        >
          <view class="picker">
            {{ resultOptions[formData.F_Level]?.name || '请选择检疫结果' }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">检疫证明上传</text>
        <view class="image-upload" :class="{ 'uploading': isUploading }">
          <img 
            v-if="formData.F_ResultImage" 
            :src="formData.F_ResultImage" 
            alt="检疫证明" 
            class="upload-image" 
            @click="triggerFileUpload" 
          />
          <view v-else-if="isUploading" class="uploading-mask">
            <text>上传中...</text>
          </view>
          <view v-else class="upload-placeholder" @click="triggerFileUpload">
            <text>+</text>
            <text class="upload-text">点击上传</text>
          </view>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">检疫时间</text>
        <picker 
          mode="date" 
          :value="formData.F_StTime" 
          start="2020-01-01" 
          end="2030-12-31" 
          @change="onDateChange"
        >
          <view class="picker">
            {{ formData.F_StTime || '请选择检疫时间' }}
          </view>
        </picker>
      </view>
      
      <InfoTitleList :infoTitleList="animalInfoList1"></InfoTitleList>
      
      <view class="form-item">
        <text class="label">选择牲畜</text>
        <CattleDropdown 
          :cattleList="cattleList" 
          @select="handleCattleSelect" 
          :placeholder="'请选择牲畜'"
        />
      </view>
      
      <view class="form-item form-item-row">
        <text class="label">备注</text>
        <view class="flex-1">
          <textarea v-model="formData.F_Remark" placeholder="请输入备注信息" class="textarea" />
        </view>
      </view>
    </view>
    
    <view class="header">
      <button class="add-button" @click="submitForm">确定提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import InfoTitleList from '@/components/Animals/InfoTitleList.vue';
import CattleDropdown from '@/components/Quarantinehome/CattleDropdown.vue';
import { addQuarantine } from '/api/manageLeft.js';
import { getCattleList } from '/api/manageRight.js';

const API_DOMAIN = 'http://8.137.157.16:9999';
const IMG_UPLOAD_URL = `${API_DOMAIN}/liveStock/public/imgUpload`;

const formData = ref({
  F_Stand: '',
  F_Title: '',
  F_Phone: '',
  F_Personnel: '',
  F_Level: 0, // 初始值设为0（未知），允许提交
  F_ResultImage: '',
  F_StTime: '',
  F_Address: '',
  F_liveid: '',
  F_UserName: 'admin', // 操作人，这里假设为 'admin'
  F_Remark: ''
});

const cattleList = ref([]);
const isUploading = ref(false);
const resultOptions = [
  { id: 0, name: '未知' },
  { id: 1, name: '合格' },
  { id: 2, name: '不合格' }
];

// 返回上一页
const goBack = () => uni.navigateBack();

// 加载牲畜列表
const loadCattleList = async () => {
  try {
    const response = await getCattleList();
    if (response.code === 200 && response.data) {
      cattleList.value = response.data.map(item => ({
        id: item.F_Id,
        imei: item.F_IMEI
      }));
    } else {
      uni.showToast({ title: '获取牲畜列表失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取牲畜列表错误:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};

// 触发图片上传
const triggerFileUpload = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => uploadImage(res.tempFilePaths[0]),
    fail: (err) => console.error('选择图片失败:', err)
  });
};

// 图片上传逻辑
const uploadImage = (filePath) => {
  isUploading.value = true;
  
  uni.uploadFile({
    url: IMG_UPLOAD_URL,
    filePath: filePath,
    name: 'file',
    success: (res) => {
      console.log('图片上传响应:', res.data);
      
      try {
        const response = JSON.parse(res.data);
        if (response.code === 200) {
          // 确保图片路径正确拼接
          formData.value.F_ResultImage = response.data.startsWith('http') 
            ? response.data 
            : `${API_DOMAIN}/${response.data}`;
          uni.showToast({ title: '上传成功', icon: 'success' });
        } else {
          throw new Error(response.msg || `上传失败（错误码：${response.code}）`);
        }
      } catch (error) {
        console.error('响应解析失败:', error, '原始数据:', res.data);
        uni.showToast({
          title: '上传失败，请检查文件格式或网络连接',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('上传失败:', err);
      uni.showToast({
        title: err.errMsg || '上传请求失败，请重试',
        icon: 'none'
      });
    },
    complete: () => {
      isUploading.value = false;
    }
  });
};

// 选择牲畜处理
const handleCattleSelect = (selectedCattle) => {
  if (selectedCattle) {
    formData.value.F_liveid = selectedCattle;
  } else {
    uni.showToast({ title: '请选择有效牲畜', icon: 'none' });
  }
};

// 检疫结果变更
const onResultChange = (e) => {
  formData.value.F_Level = parseInt(e.detail.value);
};

// 日期选择变更
const onDateChange = (e) => {
  formData.value.F_StTime = e.detail.value;
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  const requiredFields = [
    'F_Stand', 'F_Title', 'F_Phone', 'F_Personnel',
    'F_Level', 'F_StTime', 'F_Address', 'F_liveid',
    'F_UserName', 'F_Remark', 'F_ResultImage'
  ];

  const missing = requiredFields.filter(field => {
    const value = formData.value[field];

    // 直接检查值是否存在
    if (typeof value === 'string') {
      return value.trim() === '';
    }

    if (typeof value === 'number') {
      return isNaN(value);
    }

    return value === null || value === undefined;
  });

  if (missing.length > 0) {
    uni.showToast({
      title: `缺少必填字段：${missing.join(', ')}`,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  try {
    uni.showLoading({ title: '提交中...', mask: true });
    
    const response = await addQuarantine(formData.value);
    
    uni.hideLoading();
    
    if (response.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 1500
      });
      setTimeout(() => uni.navigateBack(), 1500);
    } else {
      uni.showToast({ title: response.msg || '添加失败', icon: 'none' });
    }
  } catch (error) {
    console.error('提交失败:', error);
    uni.hideLoading();
    uni.showToast({ title: '网络错误，请检查接口或重试', icon: 'none' });
  }
};

onMounted(() => loadCattleList());
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.bold-title {
  font-weight: bold;
}

.content-area {
  flex: 1;
  padding: 28rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 2rpx solid #eee;
}

.form-item-row {
  align-items: flex-start; // 顶部对齐
}

.label {
  font-size: 24rpx;
  color: #333;
  margin-left: 3%; 
  width: 30%;
  padding-right: 20rpx;
  padding-top: 20rpx; // 与文本域顶部对齐
}

.input, .textarea, .picker {
  font-size: 24rpx;
  color: #666;
  width: 70%;
  text-align: right;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 20rpx;
  outline: none;
}

.textarea { 
  min-height: 100rpx; 
  text-align: right;
}

.header {
  padding: 30rpx;
  background-color: white;
  z-index: 100;
}

.add-button {
  background-color: #0cb755;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx;
  width: 100%;
  font-size: 32rpx;
  position: fixed;
  bottom: 0;
  left: 0;
}

.image-upload {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  position: relative;
  
  .upload-image {
    width: 80px;
    height: 80px;
    border-radius: 8rpx;
    margin-left: 20rpx;
    cursor: pointer;
  }
  
  .upload-placeholder {
    width: 80px;
    height: 80px;
    border-radius: 8rpx;
    border: 1px dashed #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
    margin-left: 20rpx;
    cursor: pointer;
    
    text:first-child { font-size: 28rpx; }
    .upload-text { font-size: 20rpx; }
  }
  
  .uploading-mask {
    position: absolute;
    right: 20rpx;
    top: 0;
    width: 80px;
    height: 80px;
    background-color: rgba(0,0,0,0.5);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8rpx;
    z-index: 10;
    font-size: 24rpx;
  }
}

.flex-1 {
  flex: 1;
}
</style>